<?php

namespace app\admin\controller;

use app\admin\model\CustomPostUsers;
use app\admin\model\LinksMessage;
use app\admin\model\Location;
use app\admin\model\MemberLevel;
use app\admin\model\OrderType;
use app\admin\model\PostClickShare;
use app\admin\model\PostPath;
use app\admin\model\Resource;
use app\admin\model\ResourceCate;
use app\admin\model\ResourceCheck;
use app\admin\model\ResourceClickShare;
use app\admin\model\ResourceCollect;
use app\admin\model\ResourcePath;
use app\admin\model\ResourceRecommend;
use app\admin\model\TodayHot;
use app\admin\model\UsersMember;
use app\admin\validate\Resource as resourceValidate;
use app\admin\validate\TodayHot as todayHotValidate;
use app\AdminController;
use app\AliOosFile;
use app\index\controller\TimedTask;
use app\admin\model\Post;
use app\index\controller\Wechat;
use app\index\model\Order;
use app\index\model\PostCate;
use app\index\model\PostComment;
use app\index\model\PostLike;
use app\index\model\ResourceCheckPath;
use app\index\model\SensitiveWord;
use app\index\model\UsersLoginRecordModel;
use app\index\model\UsersModel;
use app\index\validate\Post as PostValidate;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use wxpay\Wxrefund;
use wxpay\Wxsend;

/**
 * 控制台
 * Class Console
 * @package app\admin\controller
 */
class Console extends AdminController
{

    /**
     * 社群列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['name|founder', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = Resource::where($where)->order('create_time', 'desc')->where('status', '<>', -1)->page($page, $limit)->select();
        $html = '<span style="color:#23c6c8"> | </span>';
        foreach ($list as $k => $v) {
            $cidArr = explode(',', $v['cids']);
            $cateInfo = '';
            foreach ($cidArr as $cids) {
                $name = ResourceCate::where('id', $cids)->value('name');
                $cateInfo .= $name . $html;
            }
            $list[$k]['cateInfo'] = rtrim($cateInfo, $html);
            // 是否存在 检索栏 推荐列表
            $search = ResourceRecommend::where(['rid' => $v['id'], 'type' => 1])->find();
            $list[$k]['search'] = !empty($search) ? 1 : 0;
            // 是否存在 固定栏 推荐列表
            $fixed = ResourceRecommend::where(['rid' => $v['id'], 'type' => 2])->find();
            $list[$k]['fixed'] = !empty($fixed) ? 1 : 0;
            $list[$k]['images'] = config('url.url') . ResourcePath::where(['rid' => $v['id'], 'type' => 1])->value('path');
            $list[$k]['qrcode'] = config('url.url') . $v['qrcode'];
            // 点击
            $list[$k]['click'] = ResourceClickShare::where(['rid' => $v['id'], 'type' => 1])->sum('nums');
            // 分享
            $list[$k]['share'] = ResourceClickShare::where(['rid' => $v['id'], 'type' => 2])->sum('nums');
            // 收藏
            $list[$k]['collect'] = ResourceCollect::where(['rid' => $v['id']])->count();
        }
        $count = Resource::where($where)->where('status', '<>', -1)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view();
    }

    /**
     * 添加社群
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceAdd()
    {
        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(resourceValidate::class)->sceneInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (intval($data['uid']) < 1) {
                $this->error('别闹，请认真输入用户ID');
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $res = Resource::create($data);
            if (!$res) {
                $this->error('操作失败');
            }
            $imageArr = explode(',', $data['images']);
            // 上传了视频
            if (isset($data['video']) && !empty($data['video'])) {
                $imageArr['video'] = $data['video'];
            }

            if (!empty($imageArr)) {
                // 存储图片/视频路径到指定表
                foreach ($imageArr as $type => $path) {
                    // 存储值：图片 => 1   视频 => 2
                    $type = $type === 'video' ? 2 : 1;
                    ResourcePath::create([
                        'path' => $path,
                        'type' => $type,
                        'rid' => $res->id,
                    ]);
                }
            }

            // 存储图片/视频到阿里云
            $imageArr[] = $data['qrcode'];
            if (!empty($imageArr)) {
                foreach ($imageArr as $url) {
                    $AliOos = new AliOosFile();
                    // 去除开头的 /
                    $urls = substr($url, 1);
                    $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $url, $urls);
                }
            }

            $this->success('操作成功', url('/console/index'));
        }

        // 一级分类
        $topCate = ResourceCate::where('pid', 0)->select();
        // 省份
        $province = Location::getProvince();
        return view('', ['topCate' => $topCate, 'province' => $province]);
    }

    /**
     * 编辑社群
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceEdit()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = Resource::find($id);
        $info['yqrcode'] = config('url.url') . $info['qrcode'];

        // 格式化图片和视频
        $path_list = ResourcePath::where(['rid' => $info['id']])->hidden(['create_time'])->select();
        $path_list = $path_list ? $path_list->toArray() : [];
        $info['images_list'] = '';
        $info['images_path'] = '';
        $info['video'] = '';
        $info['video_path'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            $images_path = '';
            foreach ($path_list as $v) {
                if ($v['type'] == 1) {
                    $path .= config('url.url') . $v['path'] . ',';
                    $images_path .= $v['path'] . ',';
                    $yImagesArr[] = $v['path'];
                } else {
                    $info['video'] = $v['path'];
                    $info['video_path'] = config('url.url') . $v['path'];
                }
            }
            $info['images_list'] = rtrim($path, ',');
            $info['images_path'] = rtrim($images_path, ',');
        }

//        // 格式化图片和视频
//        $path_list = ResourcePath::where('rid', $info['id'])->hidden(['create_time'])->select();
//        $path_list = $path_list ? $path_list->toArray() : [];
//        $info['images'] = '';
//        $info['video'] = '';
//        $yImagesArr = [];
//        if ($path_list) {
//            $path = '';
//            foreach ($path_list as $v) {
//                if ($v['type'] == 1) {
//                    $path .= config('url.url') . $v['path'] . ',';
//                    $yImagesArr[] = $v['path'];
//                } else {
//                    $info['video'] = config('url.url') . $v['path'];
//                }
//            }
//            $info['images'] = rtrim($path, ',');
//        }


        if (request()->isPost()) {
            $data = request()->post();
//            var_dump($data);

            try {
                validate(resourceValidate::class)->sceneEdit()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (intval($data['uid']) < 1) {
                $this->error('别闹，请认真输入用户ID');
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            // 启动事务
            Db::startTrans();
            try {
                Resource::update($data, ['id' => $data['id']]);

                $pathArr = [];
//                // 更改了logo
//                if ($data['logo'] != $info['logo']) {
//                    $pathArr[] = $info['logo'];
//                }
                $qrcode = '';
                // 更改了群二维码
                if ($data['qrcode'] != $info['qrcode']) {
                    $pathArr[] = $info['qrcode'];
                }
                // 更改了视频
                $addVideo = [];
                $delVideo = [];
                if ($data['video'] != $info['video']) {
                    if ($info['video']) {
                        $pathArr[] = $info['video'];
                        $delVideo[] = $info['video'];
                    }
                    if ($data['video']) {
                        $addVideo['video'] = $data['video'];
                    }
                }

                $imageArr = explode(',', $data['images']);

                // 比对是否新增了封面图片
                $addImage = array_diff($imageArr, $yImagesArr);
                $savePathArr = array_merge($addVideo, $addImage);

//                var_dump($addVideo, $yImagesArr, $imageArr, $addImage, $savePathArr);

                if ($savePathArr) {
                    // 存储图片/视频路径到指定表
                    foreach ($savePathArr as $type => $path) {
                        // 存储值：图片 => 1   视频 => 2
                        $type = $type === 'video' ? 2 : 1;
                        $addPathSql = ResourcePath::create([
                            'path' => $path,
                            'type' => $type,
                            'rid' => $data['id'],
                        ]);
//                        var_dump($addPathSql);
//                        exit;
                    }

                    if ($qrcode) {
                        $savePathArr[] = $qrcode;
                    }
                    // 存储图片/视频到阿里云
                    foreach ($savePathArr as $url) {
                        $AliOos = new AliOosFile();
                        // 去除开头的 /
                        $urls = substr($url, 1);
                        $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $url, $urls);
                    }

                }


                // 比对是否删除了封面图片
                $delImage = array_diff($yImagesArr, $imageArr);
                $delSqlPathArr = array_merge($delVideo, $delImage);
//                var_dump($pathArr, $delSqlPathArr);
//                exit;

                // 删除图片/视频所在表位置
                if ($delSqlPathArr) {
                    foreach ($delSqlPathArr as $paths) {
                        $delPathSql = ResourcePath::where(['rid' => $data['id'], 'path' => $paths])->delete();
                    }
                }

                // 删除图片/视频所在路径
                $delPathArr = array_merge($pathArr, $delImage);
                if ($delPathArr) {
                    foreach ($delPathArr as $path) {
                        Upload::delImageOrVideo($path);
                    }
                }
                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }

            $this->success('操作成功', url('/console/index'));
        }

        // 社群分类
        if ($info['cids']) {
            $cids = explode(',', $info['cids']);
            $cateInfo = [];
            foreach ($cids as $cid) {
                $cateInfo[$cid] = ResourceCate::where('id', $cid)->value('name');
            }
            $info['cateInfo'] = $cateInfo;
        }

        // 一级分类
        $topCate = ResourceCate::where('pid', 0)->select();
        // 省份
        $province = Location::getProvince();
        // 城市
        $city = Location::getCity($info['province']);
        // 地区
        $area = Location::getArea($info['city']);

        return view('', ['info' => $info, 'topCate' => $topCate, 'province' => $province, 'city' => $city, 'area' => $area]);
    }

    /**
     * 查看社群
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceShow()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = Resource::find($id);
        $info['qrcode'] = config('url.url') . $info['qrcode'];

        // 格式化图片和视频
        $path_list = ResourcePath::where('rid', $info['id'])->hidden(['create_time'])->select();
        $path_list = $path_list ? $path_list->toArray() : [];
        $info['images'] = '';
        $info['video'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            foreach ($path_list as $v) {
                if ($v['type'] == 1) {
                    $path .= config('url.url') . $v['path'] . ',';
                    $yImagesArr[] = $v['path'];
                } else {
                    $info['video'] = config('url.url') . $v['path'];
                }
            }
            $info['images'] = rtrim($path, ',');
        }

        // 社群分类
        if ($info['cids']) {
            $cids = explode(',', $info['cids']);
            $cateInfo = [];
            foreach ($cids as $cid) {
                $cateInfo[$cid] = ResourceCate::where('id', $cid)->value('name');
            }
            $info['cateInfo'] = $cateInfo;
        }

        // 省份
        $info['province'] = Location::where('location_id', $info['province'])->value('name');
        // 城市
        $info['city'] = Location::where('location_id', $info['city'])->value('name');
        // 地区
        $info['area'] = Location::where('location_id', $info['area'])->value('name');

        return view('', ['info' => $info]);
    }

    /**
     * 添加社群推荐
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addrecommend()
    {
        $param = request()->param();
        if (!$param['type'] || !$param['id']) {
            $this->error('参数错误');
        }
//        var_dump($param);
        if (request()->isPost()) {

            $find = Resource::find($param['id']);
            if (empty($find)) {
                $this->error('该数据不存在');
            }

            // 是否已推荐
            $find1 = ResourceRecommend::where(['rid' => $param['id'], 'type' => $param['type']])->find();
//            var_dump($find1);
            if (!empty($find1)) {
                $typeName = $param['type'] == 1 ? '检索栏' : '固定栏';
                $this->error('该数据已推荐到' . $typeName);
            }


            $add_time = time();
            // 推荐周期为30天
            $end_time = strtotime('+30 days', $add_time);
            $res = ResourceRecommend::create([
                'rid' => $param['id'],
                'type' => $param['type'],
                'add_time' => $add_time,
                'end_time' => $end_time,
            ]);
            if (!$res) {
                $this->error('操作失败');
            }

            $this->success('success');
        }
    }

    /**
     * 搜索栏推荐
     * @return \think\response\Json|\think\response\View
     */
    public function searchRecommend()
    {
        return $this->resourceRecommendList(1);
    }

    /**
     * 固定栏推荐
     * @return \think\response\Json|\think\response\View
     */
    public function fixedRecommend()
    {
        return $this->resourceRecommendList(2);
    }

    /**
     * 推荐列表
     * @param $type
     * @return \think\response\Json|\think\response\View
     */
    private function resourceRecommendList($type)
    {
        if (request()->isPost()) {
            $where = [];
            if (request()->param('keywords')) {
                $where[] = ['name|founder', 'like', '%' . request()->param('keywords') . '%'];
            }

            $page = input('page', 1);
            $limit = input('limit', 10);
            $list = ResourceRecommend::alias('re')
                ->join('admin_resource r', 'r.id = re.rid')
                ->field('re.*,r.name,r.founder')
                ->where($where)
                ->where('re.type', $type)
                ->page($page, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
                $list[$k]['show_time'] = $v['show_time'] > 0 ? date('Y-m-d H:i:s', $v['show_time']) : '-';
                $list[$k]['images'] = config('url.url') . ResourcePath::where(['rid' => $v['rid'], 'type' => 1])->value('path');
            }
//            var_dump($list);
//            exit;
            $count = ResourceRecommend::alias('re')
                ->join('admin_resource r', 'r.id = re.rid')
                ->where($where)
                ->where('re.type', $type)
                ->count();

            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        $view = 'search_recommend';
        if ($type == 2) {
            $view = 'fixed_recommend';
        }
        return view($view);
    }

    /**
     * 取消社群推荐
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancelRecommend()
    {
        if (request()->isPost()) {
            $param = request()->param();
            $find = ResourceRecommend::find($param['id']);

            if (empty($find)) {
                $this->error('该数据不存在');
            }

            $res = ResourceRecommend::destroy($param['id']);

            if (!$res) {
                $this->error('操作失败');
            }

            // 重新执行推荐
            if ($param['type'] == 1) {
                TimedTask::search_recommended();
            } else {
                TimedTask::fixed_recommended();
            }

            $this->success('success');
        }
    }

    /**
     * 社群审核列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function check()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['name|founder', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = ResourceCheck::where($where)->order('create_time', 'desc')->page($page, $limit)->where('status', '<>', 2)->select();
        $html = '<span style="color:#23c6c8"> | </span>';
        foreach ($list as $k => $v) {
            $cidArr = explode(',', $v['cids']);
            $cateInfo = '';
            foreach ($cidArr as $cids) {
                $name = ResourceCate::where('id', $cids)->value('name');
                $cateInfo .= $name . $html;
            }
            $list[$k]['cateInfo'] = rtrim($cateInfo, $html);
            $province = Location::where('location_id', $v['province'])->value('name');
            $city = Location::where('location_id', $v['city'])->value('name');
            $area = Location::where('location_id', $v['area'])->value('name');
            $list[$k]['address'] = $province . $city . $area . $v['location'];
            $list[$k]['images'] = config('url.url') . ResourceCheckPath::where(['rid' => $v['id'], 'type' => 1])->value('path');
            $list[$k]['qrcode'] = config('url.url') . $v['qrcode'];
        }
        $count = ResourceCheck::where($where)->where('status', '<>', 2)->count();
        $check_count = ResourceCheck::where($where)->where('status', 0)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list, 'check_count' => $check_count]]);
        }
        return view();
    }

    /**
     * 社群驳回列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rejectList()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['name|founder', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = ResourceCheck::where($where)->where('status', -1)->page($page, $limit)
            ->order('reject_time','desc')->select();
        foreach ($list as $k => $v) {
            $list[$k]['reject_time'] = date('Y-m-d H:i:s', $v['reject_time']);
        }
        $count = ResourceCheck::where($where)->where('status', -1)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view('reject');
    }

    /**
     * 查看驳回详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function rejectShow()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = ResourceCheck::find($id);
        $info['qrcode'] = config('url.url') . $info['qrcode'];

        // 格式化图片和视频
        $path_list = ResourcePath::where('rid', $info['id'])->hidden(['create_time'])->select();
        $path_list = $path_list ? $path_list->toArray() : [];
        $info['images'] = '';
        $info['video'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            foreach ($path_list as $v) {
                if ($v['type'] == 1) {
                    $path .= config('url.url') . $v['path'] . ',';
                    $yImagesArr[] = $v['path'];
                } else {
                    $info['video'] = config('url.url') . $v['path'];
                }
            }
            $info['images'] = rtrim($path, ',');
        }

        // 社群分类
        if ($info['cids']) {
            $cids = explode(',', $info['cids']);
            $cateInfo = [];
            foreach ($cids as $cid) {
                $cateInfo[$cid] = ResourceCate::where('id', $cid)->value('name');
            }
            $info['cateInfo'] = $cateInfo;
        }

        // 省份
        $info['province'] = Location::where('location_id', $info['province'])->value('name');
        // 城市
        $info['city'] = Location::where('location_id', $info['city'])->value('name');
        // 地区
        $info['area'] = Location::where('location_id', $info['area'])->value('name');

        return view('', ['info' => $info]);
    }

    /**
     * 驳回删除
     */
    public function rejectDel()
    {
        $id = intval(request()->param('id'));
        // 不做真实删除   ps：后续这里需要查询推荐表是否存在该社群数据
        $info = ResourceCheck::update(['status' => 2], ['id' => $id]);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/console/rejectList'));
    }


    /**
     * 编辑审核社群
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkEdit()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = ResourceCheck::find($id);
        $info['yqrcode'] = config('url.url') . $info['qrcode'];

        // 格式化图片和视频
        $path_list = ResourceCheckPath::where(['rid' => $info['id']])->hidden(['create_time'])->select();
        $path_list = $path_list ? $path_list->toArray() : [];
        $info['images_list'] = '';
        $info['images_path'] = '';
        $info['video'] = '';
        $info['video_path'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            $images_path = '';
            foreach ($path_list as $v) {
                if ($v['type'] == 1) {
                    $path .= config('url.url') . $v['path'] . ',';
                    $images_path .= $v['path'] . ',';
                    $yImagesArr[] = $v['path'];
                } else {
                    $info['video'] = $v['path'];
                    $info['video_path'] = config('url.url') . $v['path'];
                }
            }
            $info['images_list'] = rtrim($path, ',');
            $info['images_path'] = rtrim($images_path, ',');
        }


        if (request()->isPost()) {
            $data = request()->post();
//            var_dump($data);exit;

            try {
                validate(resourceValidate::class)->sceneEdit()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (intval($data['uid']) < 1) {
                $this->error('别闹，请认真输入用户ID');
            }

            // 启动事务
            Db::startTrans();
            try {
                ResourceCheck::update($data, ['id' => $data['id']]);

                $pathArr = [];
                // 更改了logo
//                if ($data['logo'] != $info['logo']) {
//                    $pathArr[] = $info['logo'];
//                }
                $qrcode = '';
                // 更改了群二维码
                if ($data['qrcode'] != $info['qrcode']) {
                    $pathArr[] = $info['qrcode'];
                    $qrcode = $info['qrcode'];
                }
                // 更改了视频
                $addVideo = [];
                $delVideo = [];
                if ($data['video'] != $info['video']) {
                    if ($info['video']) {
                        $pathArr[] = $info['video'];
                        $delVideo[] = $info['video'];
                    }
                    if ($data['video']) {
                        $addVideo['video'] = $data['video'];
                    }
                }

                $imageArr = explode(',', $data['images']);

                // 比对是否新增了封面图片
                $addImage = array_diff($imageArr, $yImagesArr);
                $savePathArr = array_merge($addVideo, $addImage);

//                var_dump($addVideo, $yImagesArr, $imageArr, $addImage, $savePathArr);

                if ($savePathArr) {
                    // 存储图片/视频路径到指定表
                    foreach ($savePathArr as $type => $path) {
                        // 存储值：图片 => 1   视频 => 2
                        $type = $type === 'video' ? 2 : 1;
                        $addPathSql = ResourceCheckPath::create([
                            'path' => $path,
                            'type' => $type,
                            'rid' => $data['id'],
                        ]);
//                        var_dump($addPathSql);
//                        exit;
                    }

                    if ($qrcode) {
                        $savePathArr[] = $qrcode;
                    }
                    // 存储图片/视频到阿里云
                    foreach ($savePathArr as $url) {
                        $AliOos = new AliOosFile();
                        // 去除开头的 /
                        $urls = substr($url, 1);
                        $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $url, $urls);
                    }

                }


                // 比对是否删除了封面图片
                $delImage = array_diff($yImagesArr, $imageArr);
                $delSqlPathArr = array_merge($delVideo, $delImage);
//                var_dump($pathArr, $delSqlPathArr);
//                exit;

                // 删除图片/视频所在表位置
                if ($delSqlPathArr) {
                    foreach ($delSqlPathArr as $paths) {
                        $delPathSql = ResourceCheckPath::where(['rid' => $data['id'], 'path' => $paths])->delete();
                    }
                }

                // 删除图片/视频所在路径
                $delPathArr = array_merge($pathArr, $delImage);
                if ($delPathArr) {
                    foreach ($delPathArr as $path) {
                        Upload::delImageOrVideo($path);
                    }
                }
                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }

            $this->success('操作成功', url('/console/check'));
        }

        // 社群分类
        if ($info['cids']) {
            $cids = explode(',', $info['cids']);
            $cateInfo = [];
            foreach ($cids as $cid) {
                $cateInfo[$cid] = ResourceCate::where('id', $cid)->value('name');
            }
            $info['cateInfo'] = $cateInfo;
        }

        // 一级分类
        $topCate = ResourceCate::where('pid', 0)->select();
        // 省份
        $province = Location::getProvince();
        // 城市
        $city = Location::getCity($info['province']);
        // 地区
        $area = Location::getArea($info['city']);

        return view('', ['info' => $info, 'topCate' => $topCate, 'province' => $province, 'city' => $city, 'area' => $area]);
    }

    /**
     * 社群通过
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pass()
    {
        if (request()->isPost()) {
            $id = request()->param('id');
            $find = ResourceCheck::find($id);

            if (empty($find)) {
                $this->error('该数据不存在');
            }

            // 消息推送
            $keyword1 = '您好，您的社群申请已审核';
            $keyword2 = '通过';
            $keyword3 = $find['founder'];
            $keyword4 = $find['name'] . '（社群申请）';
            $keyword5 = '';

            // 启动事务
            Db::startTrans();
            try {

                ResourceCheck::update(['status' => 1, 'check_time' => time()], ['id' => $id]);

                $data = $find->toArray();

                $imageArr = ResourceCheckPath::where('rid', $data['id'])->hidden(['id', 'rid'])->select();
                $imageArr = $imageArr ? $imageArr->toArray() : [];
//                var_dump($imageArr);exit;
                unset($data['id'], $data['reject_reason'], $data['check_time']);

                $data['create_time'] = strtotime($data['create_time']);
                $data['update_time'] = strtotime($data['update_time']);
                $data['status'] = 1;

                $res = Resource::create($data);

                // 存储图片/视频路径到指定表
                foreach ($imageArr as $val) {
                    ResourcePath::create([
                        'path' => $val['path'],
                        'type' => $val['type'],
                        'create_time' => strtotime($val['create_time']),
                        'rid' => $res->id,
                    ]);
                }

                // 消息中心
                LinksMessage::create([
                    'title' => '社群申请',
                    'content' => $keyword1 . $keyword2 . '，社群名称：' . $find['name'],
                    // 消息推送对象 1全部  2会员  3个别
                    'push_type' => 3,
                    // 数据所属表 0通用  1社群  2社群审核  3帖子
                    'belong' => 1,
                    'uids' => $find['uid'],
                    'ids' => $res->id
                ]);

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }


            $users = UsersModel::where('id', $find['uid'])->find();
//            if ($users['pub_openid']) {
//                $send = new Wxsend();
//                $send->sendMsg($users['pub_openid'],3,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5);
//            }

            $this->success('success');
        }

    }

    /**
     * 社群驳回
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function reject()
    {
        if (request()->isPost()) {
            $param = request()->param();
            $find = ResourceCheck::find($param['id']);

            if (empty($find)) {
                $this->error('该数据不存在');
            }

            // 公众号才推送
            $keyword1 = '您好，您的社群申请已审核';
            $keyword2 = '驳回';
            $keyword3 = $find['founder'];
            $keyword4 = $find['name'] . '（社群申请）';
            $keyword5 = $param['reject_reason'];

            Db::startTrans();
            try {
                ResourceCheck::update(['status' => -1, 'reject_time' => time(), 'reject_reason' => $param['reject_reason']], ['id' => $param['id']]);

                // 消息中心
                LinksMessage::create([
                    'title' => '社群申请',
                    'content' => $keyword1 . $keyword2 . '，社群名称：' . $find['name'] . '，驳回原因：' . $keyword5,
                    // 消息推送对象 1全部  2会员  3个别
                    'push_type' => 3,
                    // 数据所属表 0通用  1社群  2社群审核  3帖子
                    'belong' => 2,
                    'uids' => $find['uid'],
                    'ids' => $find['id'],
                ]);

                Db::commit();

            } catch (\Exception $e) {
                Db::rollback();
                Log::write($e->getMessage(), 'error');
                $this->error('操作失败');

            }

            $users = UsersModel::where('id', $find['uid'])->find();
//            if ($users['pub_openid']) {
//                $send = new Wxsend();
//                $send->sendMsg($users['pub_openid'],3,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5);
//            }

            $this->success('success');
        }

    }


    /**
     * 获取城市
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCity()
    {
        $pid = request()->param('pid');
        $city = Location::getCity($pid);
        return json(['code' => 1, 'data' => $city]);
    }

    /**
     * 获取地区
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getArea()
    {
        $pid = request()->param('pid');
        $city = Location::getArea($pid);
        return json(['code' => 1, 'data' => $city]);
    }

    /**
     * 社群二级分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getResourceLevel()
    {
        if (!request()->isPost()) {
            $this->error('请求错误');
        }

        $pid = request()->param('pid');
        if (!$pid) {
            $this->error('参数错误');
        }

        $data = ResourceCate::where('pid', $pid)->hidden(['icon', 'create_time'])->select();
        $data = $data ? $data->toArray() : [];

        return json(['code' => 1, 'msg' => '数据列表', 'data' => $data]);
    }

    /**
     * 图片上传
     * @return array|\think\response\Json
     */
    public function imageReturn()
    {
        return Upload::uploadImages(request()->param('path'));
    }

    /**
     * 视频上传
     * @return \think\response\Json
     */
    public function videoReturn()
    {
        if (!empty($_FILES['file'])) {
            return Upload::uploadVideo($_FILES['file'], request()->param('path'));
        }
    }

    /**
     * 图片/视频删除
     */
    public function delImageOrVideo()
    {
        if (request()->isPost()) {
            $path = request()->param('path');
            if ($path) {
                return Upload::delImageOrVideo($path);
            }
        }
    }

    /**
     * 删除社群
     */
    public function resourceDel()
    {
        $id = intval(request()->param('id'));
        // 不做真实删除   ps：后续这里需要查询推荐表是否存在该社群数据
        $find = ResourceRecommend::where('rid', $id)->find();
        if (!empty($find)) {
            $sign = $find->type == 1 ? '检索栏' : '固定栏';
            $this->error('不允许的操作，该社群已存在' . $sign . '推荐列表');
        }
        $info = Resource::update(['status' => -1], ['id' => $id]);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/console/index'));
    }

    /**
     * 社群状态修改
     */
    public function resourceChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = Resource::find($id);
        if (!empty($find)) {
            $status = $find[$field] == 0 ? 1 : 0;
            Resource::where(['id' => $id])->update([$field => $status]);
        }
        echo json_encode(1);
        exit;
    }

    /**
     * 用户列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function user()
    {
        $where = [];
        // 昵称
        $keywords = trim(input('keywords', ''));
        // 账号所在端
        $associate = trim(input('associate', '-1'));
        // 账户状态
        $state = trim(input('state', '-1'));
        // 授权状态
        $status = trim(input('status', '-2'));
        if (!empty($keywords)) {
            $where[] = ['nickname', 'like', '%' . $keywords . '%'];
        }
        if ($associate != -1) {
            $where[] = ['associate', '=', $associate];
        }
        if ($state != -1) {
            $where[] = ['state', '=', $state];
        }
        if ($status != -2) {
            $where[] = ['status', '=', $status];
        }
        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = UsersModel::where($where)->where('is_virtual', 0)->whereNotIn('associate', [-1, -2])->page($page, $limit)->order('create_time', 'desc')->select();
        $list = $list ? $list->toArray() : [];
        foreach ($list as $k => $v) {
            $list[$k]['nickname'] = emojiDecode($v['nickname']);
            $last_time = UsersLoginRecordModel::where('uid', $v['id'])->order('create_time', 'desc')->value('create_time');
            $list[$k]['last_time'] = $last_time ? date('Y-m-d H:i:s', $last_time) : '-';
            $list[$k]['this_week_number'] = UsersLoginRecordModel::where('uid', $v['id'])->whereWeek('create_time')->count();
        }
        $count = UsersModel::where($where)->where('is_virtual', 0)->whereNotIn('associate', [-1, -2])->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        return view();
    }

    /**
     * 升级会员
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function upGradeMember()
    {
        $id = input('id');
        $day = input('day');
//        var_dump($id, $day);
//        exit;
        $find = UsersModel::where('id', $id)->find();
        if (empty($find)) {
            $this->error('未找到该数据');
        }
        $usersMember = UsersMember::where(['uid' => $find->id, 'is_show' => 1])->find();
        $time = $day * 3600 * 24;
        if (!empty($usersMember)) {
            //表示更新
            if ($usersMember['end_time'] > time()) {
                $endTime = $usersMember['end_time'] + $time;
            } else {
                $endTime = $time + time();
            }
            $res = UsersMember::update(['end_time' => $endTime], ['uid' => $find->id, 'is_show' => 1]);
        } else {
            $arr = [];
            $arr['uid'] = $find['id'];
            $arr['code'] = generateCode();
            $arr['start_time'] = time();
            $arr['end_time'] = $time + time();
            $arr['is_upgrade'] = 1;
            $res = UsersMember::create($arr);
        }

        if (!$res) {
            $this->error('操作失败');
        }

        $this->success('操作成功');
    }

    /**
     * 用户状态修改
     */
    public function userChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = UsersModel::find($id);
        if (empty($find)) {
            $this->error('未找到该数据');
        }

        $state = $find[$field] == 1 ? 0 : 1;
        $res = UsersModel::where(['id' => $id])->update([$field => $state]);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 会员列表
     * @return \think\response\Json|\think\response\View
     */
    public function member()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['u.nickname', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = UsersMember::alias('m')
            ->join('admin_users u', 'm.uid = u.id', 'left')
            ->field('m.id as mid,m.uid,m.start_time,m.end_time,u.*')
            ->where($where)
            // 是否显示 1显示 0隐藏
            ->where('m.is_show',1)
            ->page($page, $limit)
            ->where('m.end_time', '>', time())
            ->order('u.create_time','desc')
            ->select();
        $list = $list ? $list->toArray() : [];
        foreach ($list as $k => $v) {
            $list[$k]['nickname'] = emojiDecode($v['nickname']);
            $last_time = UsersLoginRecordModel::where('uid', $v['id'])->order('create_time', 'desc')->value('create_time');
            $list[$k]['last_time'] = $last_time ? date('Y-m-d H:i:s', $last_time) : '-';
            $list[$k]['this_week_number'] = UsersLoginRecordModel::where('uid', $v['id'])->whereWeek('create_time')->count();
            $new_time = $v['end_time'] - time();
            // 会员天数
            $member_day = round($new_time / 86400);
            // 会员套餐
            $mid = Order::where(['uid' => $v['id'], 'status' => 1])->order('price', 'desc')->value('mid');
            $unit = MemberLevel::where('id', $mid)->value('unit');
            $list[$k]['vip_meal'] = $member_day . ' / ' . '<span style="color:#23c6c8">' . $unit . '</span>';
            // 复购次数
            $list[$k]['buy_nums'] = Order::where(['uid' => $v['id'], 'status' => 1])->count();
        }
        $count = UsersMember::alias('m')->where('m.end_time', '>', time())->where('m.is_show',1)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        return view();
    }

    /**
     * 失效会员列表
     * @return \think\response\Json|\think\response\View
     */
    public function failMember()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['u.nickname', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = UsersMember::alias('m')
            ->join('admin_users u', 'm.uid = u.id', 'left')
            ->field('m.id as mid,m.uid,m.start_time,m.end_time,u.*')
            ->where($where)
            ->where('m.is_show', 1)
            ->page($page, $limit)
            ->where('m.end_time', '<=', time())
            ->order('u.create_time','desc')
            ->select();
        $list = $list ? $list->toArray() : [];
        foreach ($list as $k => $v) {
            // 到期时间
            $list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            $list[$k]['nickname'] = emojiDecode($v['nickname']);
        }
        $count = UsersMember::alias('m')->where('m.is_show', 1)->where('m.end_time', '>', time())->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        return view();
    }

    /**
     * 帖子列表
     * @return \think\response\Json|\think\response\View
     */
    public function post()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['u.nickname|p.content', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        // 1正常 3下架 4通过
        $status = '1,3,4';
        $list = Post::alias('p')
            ->join('admin_users u', 'p.uid = u.id', 'left')
            ->where($where)
            ->whereIn('p.status', $status)
            ->field('p.*,u.id as uuid,u.nickname')
            ->order('p.create_time', 'desc')
            ->page($page, $limit)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['nickname'] = emojiDecode($v['nickname']);
            $list[$k]['cate'] = PostCate::where('id', $v['pcid'])->value('name');
            $path = PostPath::where(['post_id' => $v['id'], 'type' => 1])->value('path');
            $list[$k]['images'] = [];
            if ($path) {
                $list[$k]['images'] = config('url.url') . $path;
            }
            // 评论
            $list[$k]['comment'] = PostComment::where('post_id', $v['id'])->count();
            // 点击
            $list[$k]['click'] = PostClickShare::where(['post_id' => $v['id'], 'type' => 1])->sum('nums');
            // 点赞
            $list[$k]['like'] = PostLike::where(['post_id' => $v['id']])->count();
            // 分享
            $list[$k]['share'] = PostClickShare::where(['post_id' => $v['id'], 'type' => 2])->sum('nums');
        }
        $count = Post::alias('p')->where($where)->whereIn('p.status', $status)->join('admin_users u', 'p.uid = u.id', 'left')->count();

        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view();
    }

    // 测试使用
    public function ttss()
    {
        exit;
        $hostdir = './custom/';
        $files = scandir($hostdir);
        $txt = file_get_contents('./1.txt');
        $arr = explode("\r\n", $txt);
        $arr1 = [];
        foreach ($files as $v) {
            if ($v != '.' && $v != '..') {
                $arr1[] = $v;
//
            }
        }

        $combine = array_combine($arr, $arr1);
//            var_dump($arr1,$combine);
        $key = 0;
        foreach ($combine as $name => $path) {

            $path1 = '/public/custom/' . $path;
            $path2 = '/custom/' . $path;
            $res = CustomPostUsers::create([
                'custom_id' => 'CT-' . ++$key,
                'name' => $name,
                'headpath' => $path1,
            ]);
//                $urls = substr($path1, 1);
//
//                var_dump($urls,$_SERVER['DOCUMENT_ROOT'] . $path2);
//                exit;
            if ($res) {
                Log::write('正在写入' . $name . '的数据', 'error');
                $AliOos = new AliOosFile();
                // 去除开头的 /
                $urls = substr($path1, 1);
                $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $path2, $urls);
            }
        }

        exit;


        $all = CustomPostUsers::select()->toArray();
        foreach ($all as $v) {
            UsersModel::create([
                'nickname' => $v['name'],
                'headimg' => 'https://yunliuns.oss-cn-shenzhen.aliyuncs.com' . $v['headpath'],
                'is_virtual' => 1,
            ]);
        }

    }

    /**
     * 添加帖子
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postAdd()
    {
        if (request()->isPost()) {
            $param = request()->post();

            // 必须上传其一
            if (empty($param['images']) && empty($param['content']) && empty($param['video'])) {
                $this->error('随便发布点东西吧');
            }

            if (isset($param['content']) && !empty($param['content'])) {
                // 本地测试不请求微信检测
                if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
                    $wechat = new Wechat();
                    $wxToken = $wechat->GetToken1();
                    if (!$wxToken) {
                        Log::write('addPost_token:' . json_encode($wxToken), 'error');
                        $this->error(10500, '验证标识出错');
                    }

                    $postData = json_encode(['content' => $param['content']], JSON_UNESCAPED_UNICODE);
                    // 内容安全接口 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html
                    // 频率限制：单个 appId 调用上限为 4000 次/分钟，2,000,000 次/天
                    $url1 = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s";
                    $checkUrl = sprintf($url1, $wxToken);
                    $contentRes = httpCurl($checkUrl, $postData, 'POST');
                    $contentRes = json_decode($contentRes, true);
                    Log::write('后台内容安全结果:' . json_encode($contentRes), 'error');
                    // 87014 => 内容含有违法违规内容
                    if ($contentRes['errcode'] == 87014) {
                        // 存储违规词
                        $finds = SensitiveWord::where('badword', $param['content'])->find();
                        if (empty($finds)) {
                            SensitiveWord::create([
                                'badword' => $param['content'],
                            ]);
                        }
                        Log::write('后台帖子添加-wx_content_errmsg：' . json_encode($contentRes), 'error');
                        $this->error(10500, '存在违规词汇1');
                    }
                }
            }

            try {
                validate(PostValidate::class)->sceneInsert()->check($param);
            } catch (ValidateException $e) {
                $this->error(10500, $e->getMessage());
            }

            // 启动事务
            Db::startTrans();
            try {

                $param['status'] = $param['is_custom'] = 1;
                $usersModel = new UsersModel();
                $all = $usersModel->getVirtual();
                $key = array_rand($all, 1);
                $param['uid'] = $all[$key]['id'];

                $res = Post::create($param);
                if (!$res) {
                    $this->error('操作失败');
                }
                $imageArr = [];
                // 上传了图片
                if (isset($param['images']) && !empty($param['images'])) {
                    $imageArr = explode(',', $param['images']);
                }
                // 上传了视频
                if (isset($param['video']) && !empty($param['video'])) {
                    $imageArr['video'] = $param['video'];
                }

                if (!empty($imageArr)) {
                    // 存储图片/视频路径到指定表
                    foreach ($imageArr as $type => $path) {
                        // 存储值：图片 => 1   视频 => 2
                        $type = $type === 'video' ? 2 : 1;
                        $width = 0;
                        $height = 0;
                        if ($type == 1) {
                            Log::write('正在获取' . $path . '的图片', 'error');
                            $imagesInfo = getimagesize($_SERVER['DOCUMENT_ROOT'] . $path);
                            if (!is_array($imagesInfo)) {
                                Log::write('获取' . json_encode($path) . '图片信息错误' . json_encode($imagesInfo), 'error');
                            }
                            $width = $imagesInfo[0];
                            $height = $imagesInfo[1];
                        }
                        PostPath::create([
                            'path' => $path,
                            'type' => $type,
                            'post_id' => $res->id,
                            'width' => $width,
                            'height' => $height,
                        ]);
                    }

                    // 存储图片/视频到阿里云
                    foreach ($imageArr as $url) {
                        $AliOos = new AliOosFile();
                        // 去除开头的 /
                        $urls = substr($url, 1);
                        $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $url, $urls);
                    }
                }

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $error[1] = json_encode($param);
                $error[2] = $e->getMessage();
                Log::write($error, 'error');
                $this->error($e->getMessage());
            }

            $this->success('操作成功', url('/console/post'));
        }

        $postCate = PostCate::field('id,name')->select();
        return view('', ['postCate' => $postCate]);
    }


    /**
     * 帖子详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postShow()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = Post::find($id);

        // 格式化图片和视频
        $path_list = PostPath::where(['post_id' => $info['id']])->hidden(['create_time'])->select();
        $path_list = $path_list ? $path_list->toArray() : [];
        $info['images'] = '';
        $info['video'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            foreach ($path_list as $v) {
                if ($v['type'] == 1) {
                    $path .= config('url.url') . $v['path'] . ',';
                    $yImagesArr[] = $v['path'];
                } else {
                    $info['video'] = config('url.url') . $v['path'];
                }
            }
            $info['images'] = rtrim($path, ',');
        }

        // 分类
        $info['cate'] = PostCate::field('id,name')->where('id', $info['pcid'])->value('name');
        $nickname = UsersModel::where('id', $info['uid'])->value('nickname');
        $info['nickname'] = emojiDecode($nickname);
//        var_dump($info['cate']);exit;

        return view('', ['info' => $info]);
    }

    /**
     * 删除帖子
     */
    public function postDel()
    {
        $id = intval(request()->param('id'));
        // 不做真实删除   ps：后续这里需要查询推荐表是否存在该社群数据
        $info = Post::update(['status' => -1], ['id' => $id]);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/console/post'));
    }

    /**
     * 帖子审核列表
     * @return \think\response\Json|\think\response\View
     */
    public function postCheck()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['u.nickname|p.content', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        // 0待审核 2已驳回 4已通过
        $status = '0,2,4';
        $list = Post::alias('p')
            ->join('admin_users u', 'p.uid = u.id', 'left')
            ->where($where)
            ->whereIn('p.status', $status)
            ->field('p.*,u.id as uuid,u.nickname')
            ->order('p.create_time', 'desc')
            ->page($page, $limit)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['nickname'] = emojiDecode($v['nickname']);
            $list[$k]['cate'] = PostCate::where('id', $v['pcid'])->value('name');
            $path = PostPath::where(['post_id' => $v['id'], 'type' => 1])->value('path');
            $list[$k]['images'] = [];
            if ($path) {
                $list[$k]['images'] = config('url.url') . $path;
            }

        }
        $count = Post::alias('p')->where($where)->whereIn('p.status', $status)->join('admin_users u', 'p.uid = u.id', 'left')->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        return view();
    }

    /**
     * 编辑审核帖子
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postCheckEdit()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = Post::find($id);

        // 格式化图片和视频
        $path_list = PostPath::where(['post_id' => $info['id']])->hidden(['create_time'])->select();
        $path_list = $path_list ? $path_list->toArray() : [];
        $info['images'] = '';
        $info['video'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            foreach ($path_list as $v) {
                if ($v['type'] == 1) {
                    $path .= config('url.url') . $v['path'] . ',';
                    $yImagesArr[] = $v['path'];
                } else {
                    $info['video'] = config('url.url') . $v['path'];
                }
            }
            $info['images'] = rtrim($path, ',');
        }


        if (request()->isPost()) {
            $data = request()->post();
//            var_dump($data);

            try {
                validate(PostValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            // 启动事务
            Db::startTrans();
            try {
                Post::update($data, ['id' => $data['id']]);

                $pathArr = [];
                // 更改了视频
                $addVideo = [];
                $delVideo = [];
                if ($data['video'] != $info['video']) {
                    if ($info['video']) {
                        $pathArr[] = $info['video'];
                        $delVideo[] = $info['video'];
                    }
                    if ($data['video']) {
                        $addVideo['video'] = $data['video'];
                    }
                }

                $imageArr = explode(',', $data['images']);

                // 比对是否新增了封面图片
                $addImage = array_diff($imageArr, $yImagesArr);
                $savePathArr = array_merge($addVideo, $addImage);

//                var_dump($addVideo, $yImagesArr, $imageArr, $addImage, $savePathArr);

                if ($savePathArr) {
                    // 存储图片/视频路径到指定表
                    foreach ($savePathArr as $type => $path) {
                        // 存储值：图片 => 1   视频 => 2
                        $type = $type === 'video' ? 2 : 1;
                        $addPathSql = PostPath::create([
                            'path' => $path,
                            'type' => $type,
                            'post_id' => $data['id'],
                        ]);
//                        var_dump($addPathSql);
//                        exit;
                    }

                    // 存储图片/视频到阿里云
                    foreach ($savePathArr as $url) {
                        $AliOos = new AliOosFile();
                        // 去除开头的 /
                        $urls = substr($url, 1);
                        $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $url, $urls);
                    }

                }


                // 比对是否删除了封面图片
                $delImage = array_diff($yImagesArr, $imageArr);
                $delSqlPathArr = array_merge($delVideo, $delImage);
//                var_dump($pathArr, $delSqlPathArr);
//                exit;

                // 删除图片/视频所在表位置
                if ($delSqlPathArr) {
                    foreach ($delSqlPathArr as $paths) {
                        $delPathSql = PostPath::where(['post_id' => $data['id'], 'path' => $paths])->delete();
                    }
                }

                // 删除图片/视频所在路径
                $delPathArr = array_merge($pathArr, $delImage);
                if ($delPathArr) {
                    foreach ($delPathArr as $path) {
                        Upload::delImageOrVideo($path);
                    }
                }
                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }

            $this->success('操作成功', url('/console/postcheck'));
        }

        // 分类
        $cate = PostCate::field('id,name')->select();

        return view('', ['info' => $info, 'cate' => $cate]);
    }


    /**
     * 帖子通过
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postPass()
    {
        if (request()->isPost()) {
            $id = request()->param('id');
            $find = Post::find($id);

            if (empty($find)) {
                $this->error('该数据不存在');
            }

            // 启动事务
            Db::startTrans();
            try {

                Post::update(['status' => 4, 'check_time' => time()], ['id' => $id]);


                /****** 需求更改，以下操作暂时不做 ******/
//                $data = $find->toArray();
//
//                $imageArr = PostPath::where('post_id', $data['id'])->hidden(['id', 'rid'])->select();
//                $imageArr = $imageArr ? $imageArr->toArray() : [];
////                var_dump($imageArr);exit;
//                unset($data['id'], $data['reject_reason'], $data['check_time']);
//
//                $data['create_time'] = strtotime($data['create_time']);
//                $data['update_time'] = strtotime($data['update_time']);
//                $data['status'] = 1;
//
//                $res = Post::create($data);
//
//                // 存储图片/视频路径到指定表
//                foreach ($imageArr as $val) {
//                    PostPath::create([
//                        'path' => $val['path'],
//                        'type' => $val['type'],
//                        'create_time' => strtotime($val['create_time']),
//                        'post_id' => $res->id,
//                    ]);
//                }

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }

//            // 公众号才推送
//            $keyword1 = '您的帖子申请已审核';
//            $keyword2 = '通过';
//            $keyword5 = '';
//            $users = UsersModel::where('id',$find['uid'])->find();
//            if ($users['pub_openid']) {
//                Log::write('存在openid'.json_encode($users['pub_openid']),'error');
//                $send = new Wxsend();
//                $send->sendMsg($users['pub_openid'],14,$keyword1,$keyword2,'','',$keyword5);
//            }

            $this->success('success');
        }

    }

    /**
     * 帖子驳回
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postReject()
    {
        if (request()->isPost()) {
            $param = request()->param();
            $find = Post::find($param['id']);

            if (empty($find)) {
                $this->error('该数据不存在');
            }

            // 公众号才推送
            $keyword1 = '您好，您的帖子申请已审核';
            $keyword2 = '发布帖子';
            $keyword3 = date('Y/m/d H:i:s', strtotime($find['create_time']));
            $keyword4 = '审核驳回';
            $keyword5 = $param['reject_reason'];

            Db::startTrans();
            try {
                Post::update(['status' => 2, 'reject_time' => time(), 'reject_reason' => $param['reject_reason']], ['id' => $param['id']]);

                // 消息中心
                LinksMessage::create([
                    'title' => $keyword2,
                    'content' => $keyword1 . '驳回，驳回原因：' . $keyword5,
                    // 消息推送对象 1全部  2会员  3个别
                    'push_type' => 3,
                    // 数据所属表 0通用  1社群  2社群审核  3帖子
                    'belong' => 3,
                    'uids' => $find['uid'],
                    'ids' => $find['id']
                ]);

                Db::commit();

            } catch (\Exception $e) {
                Db::rollback();
                Log::write($e->getMessage(), 'error');
                $this->error('操作失败');

            }

            $users = UsersModel::where('id', $find['uid'])->find();
//            if ($users['pub_openid']) {
//                Log::write('存在openid'.json_encode($users['pub_openid']),'error');
//                $send = new Wxsend();
//                $send->sendMsg($users['pub_openid'],14,$keyword1,$keyword2,$keyword3,$keyword4,$keyword5);
//            }

            $this->success('success');
        }
    }

    /**
     * 今日热议
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function todayHot()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['title', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = TodayHot::where($where)->order('create_time', 'desc')->where('status', '<>', -1)->page($page, $limit)->select();
        $count = TodayHot::where($where)->count();

        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        return view();
    }

    /**
     * 添加/编辑今日热议
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function todayHotEdit()
    {
        $todayHotModel = new TodayHot();
        $id = $this->request->param('id') ? intval($this->request->param('id')) : '';

        // 默认为 "添加" 操作
        $scene = 'insert';
        $info = $todayHotModel;
        // 编辑
        if (!empty($id)) {
            $scene = 'edit';
            $info = $todayHotModel->find($id);
        }

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(todayHotValidate::class)->scene($scene)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $info->save($data);
            $this->success('操作成功', url('/console/todayHot'));
        }

        return view('', ['info' => $info]);
    }

    /**
     * 今日热议删除
     */
    public function todayHotDel()
    {
        $id = intval(request()->param('id'));
        // 不做真实删除
        $info = TodayHot::update(['status' => -1], ['id' => $id]);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/console/todayHot'));
    }

    /**
     * 今日热议状态修改
     */
    public function todayChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = TodayHot::find($id);
        if (!empty($find)) {
            $status = $find[$field] == 0 ? 1 : 0;
            TodayHot::where(['id' => $id])->update([$field => $status]);
        }
        echo json_encode(1);
        exit;
    }

    /**
     * 订单列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function order()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        $type_id = trim(input('type_id', '-1'));
        $status = trim(input('status', '-1'));
        if (!empty($keywords)) {
            $where[] = ['o.order_no', 'like', '%' . $keywords . '%'];
        }

        if ($type_id != -1) {
            $where[] = ['o.type_id', '=', $type_id];
        }

        if ($status != -1) {
            $where[] = ['o.status', '=', $status];
        }

//        var_dump($where);

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = Order::alias('o')
            ->join('admin_users u', 'o.uid = u.id', 'left')
            ->join('admin_member_level l', 'o.mid = l.id', 'left')
            ->join('admin_order_type t', 'o.type_id = t.id', 'left')
            ->where($where)
            ->where('o.status', '<>', -1)
            ->order('o.create_time', 'desc')
            ->field('o.*,u.id uuid,u.nickname,u.headimg,l.id as lid,l.level,t.name as tname')
            ->page($page, $limit)
            ->select();
//        var_dump($list);
//        exit;
        $list = $list ? $list->toArray() : [];
        foreach ($list as $k => $v) {
//            var_dump($v);
            $list[$k]['member_message'] = $v['price'] . ' / ' . '<span style="color:#23c6c8">' . $v['level'] . '</span>';
            $list[$k]['buy_message'] = '昵称：' . '<span style="color:#23c6c8">' . emojiDecode($v['nickname']) . '</span>' . '<br>' . '用户ID：<span style="color:#23c6c8">' . $v['uid'] . '</span>' . '<br>' . '<div onclick="show_img(this)" ><img src="' . $v['headimg'] . '" width="60px" height="60px"></div>';
            $list[$k]['pay_time'] = $v['pay_time'] > 0 ? date('Y-m-d H:i:s', $v['pay_time']) : '-';
        }
//        exit;
        $count = Order::alias('o')->where('o.status', '<>', -1)->where($where)->count();

        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        $orderType = OrderType::select();

        return view('', ['orderType' => $orderType]);
    }


    /**
     * 订单删除
     */
    public function delOrder()
    {
        $id = intval(request()->param('id'));
        // 不做真实删除
        $info = Order::update(['status' => -1], ['id' => $id]);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/console/order'));
    }

    /**
     * 订单去支付
     */
    public function orderChangeStatus()
    {
        $id = input('id', 0);
        $order = Order::where('id', $id)->find();
        if (empty($order)) {
            $this->error('未找到该数据');
        }
        // 会员级别
        $memberLevel = MemberLevel::where('id', $order['mid'])->find();
        Db::startTrans();
        try {
            // validity 会员天数
            if ($memberLevel['validity'] >= 1) {
                $usersMember = UsersMember::where(['uid' => $order['uid'], 'is_show' => 1])->find();
                if (!empty($usersMember)) {
                    // 更新会员到期时间
                    $endTime = UsersMember::setMemberExpireTime($memberLevel, $usersMember['end_time']);
                    $up = UsersMember::update(['end_time' => $endTime], ['uid' => $order['uid'], 'is_show' => 1]);
                    $msg = '成功更新会员到期时间';
                    if (!$up) {
                        $msg = '更新会员到期时间失败';
                    }
                    Log::write($msg, 'error');
                } else {
                    // 新会员添加
                    $endTime = UsersMember::setMemberExpireTime($memberLevel, time());
                    $cr = UsersMember::create([
                        'uid' => $order['uid'],
                        'start_time' => time(),
                        'end_time' => $endTime,
                        'code' => generateCode(),
                    ]);
                    $msg1 = '新会员添加成功';
                    if (!$cr) {
                        $msg1 = '新会员添加失败';
                    }
                    Log::write($msg1, 'error');
                }
            }

            // 修改订单状态信息
            $order->status = 1;
            $order->pay_time = time();
            $order->save();
            Log::write('订单状态更新完毕', 'error');
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage(), 'error');
            $this->error('操作失败');
        }

        $this->success('操作成功');
    }


}